//
//  UCSelectArea.m
//  SDK开发版本
//
//  Created by 北京国泰北斗科技有限公司 on 2017/2/13.
//  Copyright © 2017年 北京国泰北斗科技有限公司. All rights reserved.
//

#import "UCSelectArea.h"

#import "UCMapView.h"
#import "UCPolygon.h"
#import "UCPolyline.h"
#import "UCMeasureMarker.h"
#import "UCMarker.h"
#import "Public.h"
#import "UCMapView+GSExtension.h"
#import "TapMarkerPopView.h"
#import "UCMutablePath.h"

@interface UCSelectArea (){

    UIColor *_componentLineColor;
    UIColor *_componentFillColor;
    CGFloat _componentLineWidth;
}
@property(nonatomic,strong)UCPolygon *polygon;
@property(nonatomic,strong)UCPolyline *polyline;
@property(nonatomic,strong)NSMutableArray *labels;
///设置内容标签的显示样式
@property(nonatomic,strong)NSDictionary *attributes;
@property(nonatomic,strong)UCMeasureMarker *centerMarker;

@end

@implementation UCSelectArea


- (UCPolyline *)polyline{
    if (!_polyline) {
        _polyline = [UCPolyline new];
        if (super.componentLineColor) {
            _polyline.strokeColor = super.componentLineColor;
        }else{
            _polyline.strokeColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:1];
        }
        if (super.componentLineWidth <= 0) {
            _polyline.strokeWidth = 1.0f;
        }else{
            _polyline.strokeWidth = super.componentLineWidth;
        }
        _polyline.zIndex = 10;
    }
    return _polyline;
}

- (UCPolygon *)polygon{
    if (!_polygon) {
        _polygon = [[UCPolygon alloc] init];
        if (super.componentLineColor) {
            _polygon.strokeColor = super.componentLineColor;
        }else{
            _polygon.strokeColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:1];
        }
        if (super.componentFillColor) {
            _polygon.fillColor = super.componentFillColor;
        }else{
            _polygon.fillColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:0.32];
        }
        if (super.componentLineWidth) {
            _polygon.strokeWidth = super.componentLineWidth;
        }else{
            _polygon.strokeWidth = 1.0f;
        }
        _polygon.zIndex = 10;
    }
    return _polygon;
}
- (NSMutableArray *)labels{
    if (!_labels) {
        _labels = [[NSMutableArray alloc] init];
    }
    return _labels;
}

- (void)setComponentFillColor:(UIColor *)componentFillColor{
    super.componentFillColor = componentFillColor;
    self.polygon.fillColor = componentFillColor;
}

- (void)setComponentLineColor:(UIColor *)componentLineColor{
    super.componentLineColor = componentLineColor;
    self.polygon.strokeColor = componentLineColor;
    self.polyline.strokeColor = componentLineColor;
}

- (void)setComponentLineWidth:(CGFloat)componentLineWidth{
    super.componentLineWidth = componentLineWidth;
    self.polyline.strokeWidth = componentLineWidth;
    self.polygon.strokeWidth = componentLineWidth;
}

#pragma mark - 根据传入的点获取区域
- (void)addCoordToComponent:(CLLocationCoordinate2D)position{
    
    [super addCoordToComponent:position];
    
    if (self.markers.count == 2) {
        self.polyline.path = self.mutablePath;
        self.polyline.mapView = self.mapView;
        
        [self createMeasureLabelWithIndex1:(int)self.markers.count-2 index2:(int)self.markers.count-1];
        
    }else if (self.markers.count == 3){
        self.polyline.mapView = nil;
        self.polyline = nil;
        self.polygon.path = self.mutablePath;
        self.polygon.mapView = self.mapView;
        
        
        [self createMeasureLabelWithIndex1:(int)self.markers.count-2 index2:(int)self.markers.count-1];
        [self createMeasureLabelWithIndex1:0 index2:(int)self.markers.count-1];
        
    }else if(self.markers.count > 3){
        self.polygon.path = self.mutablePath;
        self.polygon.mapView = self.mapView;
        
        //删除最后一个标签
        if (self.labels.count > 0) {
            [[self.labels objectAtIndex:self.labels.count-1] setMap:nil];
            [self.labels removeObjectAtIndex:self.labels.count-1];
        }
        [self createMeasureLabelWithIndex1:(int)self.markers.count-2 index2:(int)self.markers.count-1];
        [self createMeasureLabelWithIndex1:0 index2:(int)self.markers.count-1];
    }
    
    //计算并设置选择区域的面积大小
    [self calculateAndSetTheAreaSizeOfTheSelectionArea:self.markers];
}

///创建显示测量数据的标签
- (void)createMeasureLabelWithIndex1:(int)index1 index2:(int)index2{
    
    if (_openContentLabel) { //如果开启标签显示功能
        //先获取线两端的marker
        UCMarker *marker1 = self.markers[index1];
        UCMarker *marker2 = self.markers[index2];
        
        NSString *string = nil;
        if (self.markers.count < 3) {
            
            string = [NSString stringWithFormat:@"%.2f米",CalculateTheDistanceOfTheLine(self.polyline.path)];
        }else if (self.polygon){
            UCMutablePath *path = [[UCMutablePath alloc] init];
            [path addCoordinate:marker1.coordinate];
            [path addCoordinate:marker2.coordinate];
            string = [NSString stringWithFormat:@"%.2f米",CalculateTheDistanceOfTheLine(path)];
        }
        //创建数据标签
        UCMeasureMarker *sureMar = [UCMeasureMarker measureMarkerWithLocation1:marker1.coordinate
                                                                     location2:marker2.coordinate
                                                                        string:string];
        if (_attributes) {
            [sureMar setContentLabelCongfig:_attributes];
        }
        sureMar.map = [self.mapView valueForKey:@"map"];
        [self.labels addObject:sureMar];
    }
}

- (void)changeCoordWhenDragMarker:(UCMarker *)marker{
    
    [super changeCoordWhenDragMarker:marker];
    
    if (self.markers.count < 3) {
        //设置线的path
        self.polyline.path = self.mutablePath;
        
        if (_openContentLabel) {
            for (UCMeasureMarker *sureMar in self.labels) {
                GMSMarker *marker1 = self.markers[0];
                GMSMarker *marker2 = self.markers[1];
                NSString *string = [NSString stringWithFormat:@"%.2f米",CalculateTheDistanceOfTheLine(self.polyline.path)];
                [sureMar changeLocationWithLocation1:marker1.position location2:marker2.position string:string];
            }
        }
    }else{
        //设置多边形的path
        self.polygon.path = self.mutablePath;
        
        if (_openContentLabel) {
            for (int i = 0; i < self.markers.count; i++) {
                UCMarker *first = [self.markers firstObject];
                UCMarker *last = [self.markers lastObject];
                UCMarker *currentMar = [self.markers objectAtIndex:i];
                
                if ([marker valueForKey:@"marker"] == [first valueForKey:@"marker"]) {
                    //如果拖拽的是第一个，那就修改labels数组中的第一个和最后一个
                    //先取第一条线 (点1和点2)
                    NSString *line1 = [self measureDisstanceFromMarker1:marker
                                                               ToMarker:self.markers[1]];
                    [[self.labels firstObject] changeLocationWithLocation1:marker.coordinate
                                                                 location2:[[self.markers objectAtIndex:1] coordinate]
                                                                    string:line1];
                    
                    //取最后一条线 (点1和最后一个点)
                    NSString *line2 = [self measureDisstanceFromMarker1:marker
                                                               ToMarker:self.markers.lastObject];
                    [[self.labels lastObject] changeLocationWithLocation1:marker.coordinate
                                                                location2:[[self.markers lastObject] coordinate]
                                                                   string:line2];
                    
                    
                }else if ([marker valueForKey:@"marker"] == [last valueForKey:@"marker"]){
                    //如果退拽的是最后一个
                    //先取出修改的第一条线 (1和最后一个点)
                    NSString *line1 = [self measureDisstanceFromMarker1:self.markers.firstObject
                                                               ToMarker:marker];
                    [self.labels.lastObject changeLocationWithLocation1:[self.markers.firstObject coordinate]
                                                              location2:marker.coordinate
                                                                 string:line1];
                    //修改的第二条线 (最后一个和倒数第二个)
                    NSString *line2 = [self measureDisstanceFromMarker1:marker
                                                               ToMarker:[self.markers objectAtIndex:self.markers.count-2]];
                    [[self.labels objectAtIndex:self.labels.count-2] changeLocationWithLocation1:marker.coordinate
                                                                                       location2:[[self.markers objectAtIndex:self.markers.count-2] coordinate]
                                                                                          string:line2];
                }else if([currentMar valueForKey:@"marker"] == [marker valueForKey:@"marker"]){
                    //中间任意的一个
                    //修改第一条线 (当前和前一个)
                    NSString *line1 = [self measureDisstanceFromMarker1:marker
                                                               ToMarker:[self.markers objectAtIndex:i-1]];
                    [[self.labels objectAtIndex:i-1] changeLocationWithLocation1:marker.coordinate
                                                                       location2:[[self.markers objectAtIndex:i-1] coordinate]
                                                                          string:line1];
                    
                    //修改第二条线
                    NSString *line2 = [self measureDisstanceFromMarker1:marker
                                                               ToMarker:[self.markers objectAtIndex:i+1]];
                    [[self.labels objectAtIndex:i] changeLocationWithLocation1:marker.coordinate
                                                                     location2:[[self.markers objectAtIndex:i+1] coordinate]
                                                                        string:line2];
                }
            }
        }
    }
    
    //计算并设置选择区域的面积大小
    [self calculateAndSetTheAreaSizeOfTheSelectionArea:self.markers];
}

///获取两个marker之间距离
- (NSString *)measureDisstanceFromMarker1:(UCMarker *)marker1 ToMarker:(UCMarker *)marker2{
    UCMutablePath *path = [UCMutablePath path];
    [path addCoordinate:marker1.coordinate];
    [path addCoordinate:marker2.coordinate];
    return [NSString stringWithFormat:@"%.2f米",CalculateTheDistanceOfTheLine(path)];
}

- (void)setContentLabelAttributes:(NSDictionary<NSString *,id> *)configDic{
    
    if (configDic == nil) {
        @throw [NSException exceptionWithName:@"AeroMapSDKError"
                                       reason:@"参数错误"
                                     userInfo:@{@"function":@"setContentLabelAttributes"}];
        return ;
    }
    if (self.labels.count == 0) {
        _attributes = configDic;
        return ;
    }
    for (UCMeasureMarker *marker in self.labels) {
        [marker setContentLabelCongfig:configDic];
    }
}

///计算并设置选择区域面积的大小
- (void)calculateAndSetTheAreaSizeOfTheSelectionArea:(NSArray *)array{
    
    if (_openContentLabel) {
        if (array.count >= 3) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                UCMarker *marker0 = [array objectAtIndex:0];
                UCMarker *marker1 = [array objectAtIndex:1];
                GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:marker0.coordinate coordinate:marker1.coordinate];
                for (int i = 2; i < array.count; i++) {
                    UCMarker *mk = [array objectAtIndex:i];
                    bounds = [bounds includingCoordinate:mk.coordinate];
                }
                //计算中心点坐标
                CLLocationDegrees latitude = (bounds.northEast.latitude - bounds.southWest.latitude)/2 + bounds.southWest.latitude;
                CLLocationDegrees longitude = (bounds.northEast.longitude - bounds.southWest.longitude)/2 + bounds.southWest.longitude;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (!_centerMarker) {
                        
                        double areaSize = CalculatePolygonArea(self.polygon.path);
                        CLLocationCoordinate2D center = CLLocationCoordinate2DMake(latitude, longitude);
                        NSString *areaSizeString = [NSString stringWithFormat:@"%.2f亩",areaSize*0.0015];
                        _centerMarker = [UCMeasureMarker measureMarkerCenterLocation:center
                                                                              string:areaSizeString];
                        _centerMarker.zIndex = 5;
                        [_centerMarker setContentLabelCongfig:@{
                                                                NSBackgroundColorAttributeName : [UIColor colorWithRed:3/255.0 green:169/255.0 blue:244/255.0 alpha:1.0],
                                                                NSForegroundColorAttributeName : [UIColor blackColor]
                                                                }];
                        _centerMarker.map = [self.mapView valueForKey:@"map"];
                    }else{
                        double areaSize = CalculatePolygonArea(self.polygon.path);
                        _centerMarker.position = CLLocationCoordinate2DMake(latitude, longitude);
                        [_centerMarker iconForText:[NSString stringWithFormat:@"%.2f亩",areaSize*0.0015]];
                    }
                });
            });
        }
    }
}

#pragma mark - 点击marker弹出视图
- (void)popViewWhenTapMarker:(UCMarker *)marker{
    
    TapMarkerPopView *popView = [[TapMarkerPopView alloc] initWithFrame:CGRectMake(35, 0, [UIScreen mainScreen].bounds.size.width-70, 186)];
    popView.center = self.mapView.center;
    [self.mapView addSubview:popView];
    
    popView.lonFiled.text = [NSString stringWithFormat:@"%.6f",marker.coordinate.longitude];
    popView.latFiled.text = [NSString stringWithFormat:@"%.6f",marker.coordinate.latitude];
    
    int tapIndex = -1;
    for (int i = 0; i < self.markers.count; i++) {
        UCMarker *myMk = [self.markers objectAtIndex:i];
        if (MARKER_EQUAL_OTHER(myMk, marker)) {
            tapIndex = i;
            popView.title.text = [NSString stringWithFormat:@"边界点%d",i+1];
        }
    }
    
    [popView confirm:^(NSString *lon, NSString *lat) {
        CLLocationDegrees latitude  = [lat doubleValue];
        CLLocationDegrees longitude = [lon doubleValue];
        
        UCMarker *mk = [self.markers objectAtIndex:tapIndex];
        mk.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
    }];
    
    [popView deletePoint:^{
        
        if (self.markers.count) {
            //从地图上删除
            UCMarker *mark = [self.markers objectAtIndex:tapIndex];
            mark.mapView = nil;
            //从数组中移除
            [self.markers removeObject:mark];
            //刷新所有的数据
            [self reloadData];
        }
    }];
}

- (void)reloadData{
    
    NSArray *tempArray = [NSArray arrayWithArray:self.markers];
    
    [self resetChoseArea];
    
    for (int i = 0; i < tempArray.count; i++) {
        UCMarker *marker = [tempArray objectAtIndex:i];
        [self addCoordToComponent:marker.coordinate];
    }
}

///重置选择区域
- (void)resetChoseArea{
    
    [super resetChoseArea];
    
    self.polyline.mapView = nil;
    self.polygon.mapView = nil;
    self.polyline = nil;
    self.polygon = nil;
    self.centerMarker.map = nil;
    self.centerMarker = nil;
    
    for (UCMeasureMarker *marker in self.labels) {
        marker.map = nil;
    }
    [self.labels removeAllObjects];
}

@end
